import React, { useEffect, useRef, useState } from 'react';
import style from './index.css';
type draggableType = {
  status: boolean;
  dx: number;
  dy: number;
};
const onMouseDown: Function =
  (ref: any, setDraggable: Function) => (e: MouseEvent) => {
    setDraggable({
      dy: e.clientY - ref.current.offsetTop,
      dx: e.clientX - ref.current.offsetLeft,
      status: true,
    });
    ref.current.style.cursor = 'grab';
  };

const onMouseMove: Function =
  (ref: any, draggable: draggableType) => (e: MouseEvent) => {
    if (draggable.status) {
      const div = ref.current;
      div.style.top = `${e.clientY - draggable.dy}px`;
      div.style.left = `${e.clientX - draggable.dx}px`;
    }
  };

const onMouseUp: Function =
  (ref: any, draggable: draggableType, setDraggable: Function) => () => {
    setDraggable({
      ...draggable,
      status: false,
    });
    ref.current.style.cursor = 'pointer';
  };

export default function MyComponenet(props: any) {
  const [draggable, setDraggable] = useState({
    status: false,
    dy: 0,
    dx: 0,
  });
  const ref = useRef(null);
  const handleMouseMove = () => {
    if (draggable.status === true) {
      onMouseMove(ref, draggable);
    }
  };
  useEffect(() => {
    document.addEventListener('mousemove', handleMouseMove);
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, []);
  return (
    <div
      ref={ref}
      className={style['drag-div']}
      style={{
        position: 'fixed',
        left: 200,
        top: 200,
        width: 200,
        height: 200,
        background: 'tomato',
      }}
      onMouseDown={onMouseDown(ref, setDraggable)}
      onMouseMove={onMouseMove(ref, draggable)}
      onMouseUp={onMouseUp(ref, draggable, setDraggable)}
    />
  );
}
